package cn.qg.auth.service.token;

import cn.qg.beans.pojo.QgUser;
import cn.qg.common.MD5;
import cn.qg.common.RedisAPI;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @auth amwdx
 * 2019/5/11 0011 17:50
 */

@Service
public class TokenServiceImpl implements TokenService {

    @Resource
    private RedisAPI redisAPI;
    //保存token到redis中
    @Override
    public void saveToken(String token, QgUser qgUser) throws Exception {
    // 未考虑不同客户端的存储
     redisAPI.set(token,TOKEN_EXPIRE_TIME, JSON.toJSONString(qgUser));
    }




    // 生成token   token格式:token:PC-加密的手机号-当前时间戳-六位随机数
    @Override
    public String generateToken(QgUser qgUser) throws Exception{
        StringBuffer tokenStringBuffer = new StringBuffer(TOKEN_PREFIX);
        tokenStringBuffer.append("PC-");
        tokenStringBuffer.append(MD5.getMd5(qgUser.getPhone(),32)+"-");
        tokenStringBuffer.append(qgUser.getId()+"-");
        tokenStringBuffer.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) +"-");
        // 6位随机数,例如:2344Edsf-dfsr3-123343
        tokenStringBuffer.append(UUID.randomUUID().toString().replace("-","").substring(0,6));
        return tokenStringBuffer.toString();
    }
}
